package com.gin.kotlin.no_gay_alliance.provider.ngajs

import com.gin.nga.api.ResourceApi
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.base.SingleData
import com.gin.nga.response.resource.index.ForumGroup
import com.gin.nga.response.resource.index.IndexForumsBody
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit

/**
 * 首页版面入口提供者
 * @property relativePath String
 */
class IndexForumsProvider private constructor() : AbstractNgaResourceProvider<NgaResponse<SingleData<IndexForumsBody>>, List<ForumGroup>>(
    javaType = TYPE_FACTORY.constructCollectionLikeType(List::class.java, ForumGroup::class.java),
    expires = TimeUnit.DAYS.toSeconds(1)
) {
    override val relativePath = "$DIR/indexForums.json"

    /**
     * 请求方法
     * @param resourceApi NgaApi
     * @return Call<NgaResponse<R>>
     */
    override fun requestMethod(resourceApi: ResourceApi) = resourceApi.indexForums()

    /**
     * 将响应类型转换为缓存类型的方法
     * @param res R
     * @return D
     */
    override fun transform(res: NgaResponse<SingleData<IndexForumsBody>>?) = res?.data?.data?.also { it.clear() }?.forumGroups

    companion object {
        private var instance: WeakReference<IndexForumsProvider> = WeakReference(IndexForumsProvider())

        /**
         * 单例模式+弱引用
         * @return Any
         */
        fun getInstance(): IndexForumsProvider = instance.get() ?: IndexForumsProvider().also { instance = WeakReference(it) }
    }
}